<template>
  <view class="page_min_height bg-white">
    <view class="p-12 sticky top-0 bg-white border-b border-solid border-gray-100 z-[999]">
      <scroll-view class="whitespace-nowrap overflow-x-auto" :scroll-x="true" :enhanced="true" :show-scrollbar="false">
        <view
          v-for="item in categoryList"
          :key="item.id"
          class="px-18 py-6 mr-12 inline-block last:mr-0"
          :class="{ 'bg-blue-100 text-blue-500 rounded-full': item.id === pageParams.category_id }"
          @click="changeCategory(item.id)"
        >
          <text>{{ item.name }}</text>
        </view>
      </scroll-view>
    </view>
    <DataLoading v-if="loading" />
    <template v-else>
      <template v-if="dataList.length">
        <ContractTemplateList :dataList="dataList" />
      </template>
      <view v-else class="pt-60 bg-white">
        <view class="text-gray-400 text-center">暂无购买的合同模板</view>
        <navigator url="/pages/contract/template/index" hover-class="none" open-type="switchTab">
          <view class="primary_btn w-120 mt-20 mx-auto py-6 text-center rounded-full">点击购买</view>
        </navigator>
      </view>
    </template>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { onLoad, onReachBottom } from '@dcloudio/uni-app';
import { usePage } from '@/utils/usePublic';
import { getTemplateCategoryApi, getTemplateListApi } from '@/api/contract';
import ContractTemplateList from '@/components/ContractTemplateList.vue';

const loading = ref(true);
const pageParams = usePage({
  category_id: 0,
});
const dataList = ref([]);
// 合同类别
const categoryList = ref([{ id: 0, name: '全部' }]);

onLoad(async () => {
  // 获取合同类别
  const { code, data } = await getTemplateCategoryApi({ page: 1, limit: 20 });
  if (code === 200) {
    categoryList.value = categoryList.value.concat(data.list);
  }
  getTemplateList();
});

onReachBottom(() => {
  if (pageParams.isLoadAll) {
    return;
  }
  pageParams.page += 1;
  getTemplateList();
});

async function getTemplateList() {
  const { code, data } = await getTemplateListApi({
    ...pageParams,
  });
  loading.value = false;
  if (code === 200) {
    dataList.value = dataList.value.concat(data.list);
    pageParams.isLoadAll = data.list.length < pageParams.limit;
  }
}

//  切换模板类别
function changeCategory(id) {
  loading.value = true;
  pageParams.category_id = id;
  pageParams.page = 1;
  dataList.value = [];
  getTemplateList();
}
</script>
